#include <cserver/restapi.h>
#include <boost/log/trivial.hpp>
#include <boost/lexical_cast.hpp>
#include <pqxx/transaction.hxx>
#include <boost/format.hpp>

#include <sstream>

namespace csrv{ namespace webcmd{
	static const char* K_this_command= "api/v1/light/issue_pole";

	void light_list_issue_pole(Request& req, pqxx::connection& dbconn, SessionContext& , const std::string& /*cmd*/ ){
		auto query = parseQuery(req.getParam("QUERY_STRING"));
		auto& callback = query["callback"];
		auto& section_id = query["section_id"];

		StreamGroup sg(req);
		auto& fout = sg.fout;
		response_header(sg.fout, 200);
		if (!callback.empty()) sg.fout << callback << "(";
		std::string sql = section_id.empty() ? "list_issue_pole" :  "list_issue_pole_by_section";

		pqxx::work w(dbconn);
#if 1
		std::string total;
		{
			TotalCount tc(w, sql + "_total");
			if (!section_id.empty())
				tc(section_id);
			total = tc.result();
		}
		fout << boost::format(R"({"func":"light/issue_pole",
"args":{},
"ret":{"success":true, "message":"",
"total":%1%,
"value":)") % total;
#endif
		auto result = section_id.empty() 
			? (w.prepared(sql).exec())
			: (w.prepared(sql)(section_id).exec());
		fout << result2json(result, 5);

		fout << "}}";
		if (!callback.empty()) sg.fout << ")";
	}
}

static CommandAddHelper k_registerHandler("GET", webcmd::K_this_command, &webcmd::light_list_issue_pole);
}




